<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标识名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入标识名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="控制类型" prop="control" >
          <el-select v-model="queryParams.control" placeholder="请选择控制类型" @change="handleQuery">
            <el-option value="0" label="传感器参数"></el-option>
            <el-option value="1" label="控制参数"></el-option>
            <el-option value="2" label="设置参数"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:seriesIo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:seriesIo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:seriesIo:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="seriesIoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="显示图标" align="center" prop="icon" width="100">
        <template slot-scope="scope">
          <el-image style="width: 40px; height: 40px" :src="getSensorIcon(scope.row.icon)" fit="contain"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="设备类型" align="center" prop="deviceTypeName" />
      <el-table-column label="所属产品" align="center" prop="productName" />
      <el-table-column label="标识名称" align="center" prop="name" width="250">
        <template slot-scope="scope">
          {{scope.row.name}}
          <i18n-input :objId="scope.row.id" type="com.ems.device.DeviceSeriesIo" property="DeviceSeriesIo.Name" slot="append"></i18n-input>
        </template>
      </el-table-column>
      <el-table-column label="标识" align="center" prop="flag"  />
      <el-table-column label="默认值" align="center" prop="defaultValue" ></el-table-column>
      <el-table-column label="默认单位" align="center" prop="unit" ></el-table-column>
      <el-table-column label="控制类型" align="center" prop="control" >
        <template slot-scope="scope">
          {{ controlList[scope.row.control]}}
        </template>
      </el-table-column>
      <el-table-column label="排序号" align="center" prop="orderNum" ></el-table-column>
      <el-table-column label="事件配置" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="toDisplay(scope.row)"
            v-hasPermi="['device:seriesIo:edit']"
          >显示映射</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="toEvent(scope.row)"
            v-hasPermi="['device:seriesIo:edit']"
          >告警映射</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleCopy(scope.row)"
            v-hasPermi="['device:seriesIo:edit']"
          >复制</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:seriesIo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:seriesIo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改串口Io定义对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" >
            <i18n-input :objId="form.id" type="com.ems.device.DeviceSeriesIo" property="DeviceSeriesIo.Name" slot="append" v-if="form.id"></i18n-input>
          </el-input>
        </el-form-item>
        <el-form-item label="标识" prop="flag">
          <el-input v-model="form.flag" placeholder="请输入标识" :disabled="form.subTableCreate"/>
        </el-form-item>
        <el-form-item label="计算" prop="calc"  v-if="form.control === 0">
          <el-input v-model="form.calc" placeholder="请输入通道号"/>
        </el-form-item>
        <el-form-item label="小数位" prop="decimalLength"  v-if="form.control === 0">
          <el-input-number :min="0" v-model="form.decimalLength" placeholder="请输小数位"/>
        </el-form-item>
        <el-form-item label="默认值" prop="defaultValue" v-if="form.control===1 ||form.control===2">
          <el-input v-model="form.defaultValue" placeholder="请输默认值" />
        </el-form-item>
        <el-form-item label="默认单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入默认单位" />
        </el-form-item>
        <el-form-item label="单选框选项" prop="displayModel">
          <div class="option-box">
            <el-table
              size="mini"
              :data="optionList"
              border
              style="width: 100%">
              <el-table-column label="序号" width="70" type="index" :index="indexMethod" align="center"></el-table-column>
              <el-table-column align="center"  label="变量名称">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.name" placeholder="请输入选项名" clearable>
                    <i18n-input :objId="scope.row.id" type="com.ems.device.DeviceSeriesIoCommand" property="DeviceSeriesIoCommand.Name" slot="append" v-if="scope.row.id"></i18n-input>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="表达式" v-if="form.control === 0">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.expression" placeholder="请选择显示方式">
                    <el-option
                      v-for="dict in dict.type.display_expression"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center" label="变量值">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.value" placeholder="请输入值" clearable></el-input>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" width="70" >
                <template slot-scope="scope">
                  <i class="el-icon-delete" style="cursor: pointer;" @click.stop="delOption(scope.$index,scope.row)" ></i>
                </template>
              </el-table-column>
            </el-table>
            <el-button class="add-btn" type="primary" icon="el-icon-plus" @click="addOption" >添加选项</el-button>
          </div>
        </el-form-item>
        <el-form-item label="排序号" prop="order">
          <el-input-number v-model="form.orderNum" :min="0" :max="999" label="请输入排序号"></el-input-number>
        </el-form-item>
        <el-form-item label="显示图标" prop="icon">
          <div style="width: 40px;height: 40px;cursor: pointer;margin-left: 10px;" v-show="form.icon" @click="selectIcon">
            <img style="width: 100%;height: 100%;" :src="getSensorIcon(form.icon)" alt="">
          </div>
          <el-button v-show="!form.icon" style="background-color:#03c2c2;color:#fff" @click="selectIcon" >选择</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择图标" :visible.sync="iconPopup" width="800px" append-to-body>
      <div>
        <Icon :target="form.icon" @change="onIconChange"></Icon>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelect" >确 定</el-button>
        <el-button @click="iconPopup=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 参数设置模板 -->
    <el-dialog title="参数设置模板" :visible.sync="deviceTaskVisiabled" width="1200px" append-to-body>
      <device-task v-if="deviceTaskVisiabled" :deviceId="activeId" :sensorList="sensorList" :controllerList="controllerList" :seriesIoForm="form" @success="onSelectDeviceTask" @cancel="cancelDeviceTask" ></device-task>
    </el-dialog>
    <!-- 参数设置模板 -->
    <el-dialog title="参数设置模板" :visible.sync="gwTaskVisiabled" width="1200px" append-to-body>
      <gw-task v-if="gwTaskVisiabled" :seriesIoForm="form" @success="onSelectGwTask" @cancel="cancelGwTask" ></gw-task>
    </el-dialog>
  </div>
</template>

<script>
import { listSeriesIo, getSeriesIo, delSeriesIo, addSeriesIo, updateSeriesIo ,createSubTable} from "@/api/device/seriesIo";
import { deviceTypeOptions } from "@/api/device/deviceType";
import { selectProductTree } from "@/api/device/deviceProduct";
import { getToken } from '@/utils/auth'
import Icon from '@/components/Icons/index.vue'
import deviceTask from '@/views/data/deviceData/task'
import gwTask from '@/views/data/deviceData/gw_task'
export default {
  name: "SeriesIo",
  components:{Icon,deviceTask,gwTask},
  dicts: ['control_button_display_model','series_data_type','display_expression'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      configCopy:false,
      // 总条数
      total: 0,
      // 串口Io定义表格数据
      seriesIoList: [],
      optionList:[],
      fileList:[],
      deviceTypeList:[],
      productOptions:[],
      productIds:null,
      controlList:{
        "0":"传感器参数",
        "1":"控制参数",
        "2":"设置参数"
      },
      // 弹出层标题
      title: "",
      token:'',
      parentId:null,
      productCode:null ,
      ancestors:null,
      uploadURL: process.env.VUE_APP_BASE_API + '/system/files?module=MEDIA',
      downloadUrl:process.env.VUE_APP_BASE_API + '/system/files/anonymous/download/',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        control:'0',
        pageNum: 1,
        pageSize: 10,
        seriesId: null,
        deviceTypeId:null,
        name: null,
        parentId:null
      },
      // 表单参数
      form: {
        subTableCreate:false
      },
      // 表单校验
      rules: {
        seriesId: [
          { required: true, message: "设备系列Id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "串口名称不能为空", trigger: "blur" }
        ],
        flag: [
          { required: true, message: "串口标识不能为空", trigger: "blur" }
        ],
        num: [
          { required: true, message: "串口号不能为空", trigger: "blur" }
        ],
        delFlag: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },
      iconPopup:false,
      targetIcon:'',
      //组合控制弹窗
      deviceTaskVisiabled:false,
      gwTaskVisiabled:false,
      //传感器列表
      sensorList:[],
      //控制型传感器列表
      controllerList:[],
    };
  },
  created() {
    this.queryParams.seriesId = this.$route.query.seriesId;
    this.queryParams.deviceTypeId = this.$route.query.deviceTypeId;
    this.productCode = this.$route.query.productCode;
    this.ancestors = this.$route.query.ancestors;
    this.parentId = this.$route.query.parentId;
    this.queryParams.parentId = this.parentId;
    this.getList();
    this.getDeviceTypeOptions();
    this.getControllerList()
    this.getSensorList()
    this.getProductList()
  },
  computed:{

  },
  methods: {
    /** 查询串口Io定义列表 */
    getList() {
      this.loading = true;
      listSeriesIo(this.queryParams).then(response => {
        this.seriesIoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getControllerList(){
      let queryParams = {...this.queryParams}
      queryParams.control = "1"
      queryParams.pageSize = 999
      listSeriesIo(queryParams).then(response => {
        const rows = response.rows
        let promises = []
        for (let index = 0; index < rows.length; index++) {
            const id = rows[index].id;
            promises.push(new Promise((resolve, reject)=>{
              getSeriesIo(id).then( res => {
                resolve(res.data.commandList)
              })
            }))
        }
        Promise.all(promises).then((posts)=>{
            for (let index = 0; index < posts.length; index++) {
                const commandList = posts[index];
                rows[index].commandList = commandList
            }
        })
        this.controllerList = rows;
      });
    },
    getSensorList(){
      let queryParams = {...this.queryParams}
      queryParams.control = "0"
      queryParams.pageSize = 999
      listSeriesIo(queryParams).then(response => {
        this.sensorList = response.rows;
      });
    },
    //查询设备类型
    getDeviceTypeOptions(){
      deviceTypeOptions().then( res => this.deviceTypeList = res.data.filter( o => o.seriesId === this.queryParams.seriesId))
    },
    //查询产品下拉列表
    getProductList(){
      selectProductTree({ancestors:this.ancestors}).then( res => this.productOptions = res.data)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.configCopy = false;
      this.optionList = [];
      this.form = {
        id: null,
        subTableCreate:false,
        parentId:this.parentId,
        seriesId: this.queryParams.seriesId,
        deviceTypeId:this.queryParams.deviceTypeId,
        productCode:this.productCode,
        ancestors: this.ancestors,
        name: null,
        flag: null,
        control: 0,
        dataType:null,
        decimalLength:null,
        defaultValue:null,
        unit:null,
        icon: null,
        port:null,
        displayModel: null,
        illustrate: null,
        valueStart: null,
        valueEnd: null,
        activeValue: null,
        inactiveValue: null,
        valueExpression: null,
        commandList:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.token = 'Bearer ' + getToken();
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.control = parseInt(this.queryParams.control);
      this.productIds = this.ancestors.split(',')
      this.open = true;
      this.title = "添加参数";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSeriesIo(id).then(response => {
        this.form = response.data;
        this.optionList = response.data.commandList;
        this.open = true;
        this.title = "修改参数";
        console.log(this.productIds)
        
      });
    },
    handleCopy(row){
      this.reset();
      this.configCopy = true;
      const id = row.id;
      getSeriesIo(id).then(response => {
        this.form = response.data;
        this.form.id = null ;
        if(response.data.commandList){
          this.optionList = response.data.commandList.map( o => {o.id = null ;return o;});
        }
        this.open = true;
        this.title = "复制参数";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.commandList = this.optionList;
          if (this.form.id != null) {
            updateSeriesIo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSeriesIo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除参数编号为"' + ids + '"的数据项？').then(function() {
        return delSeriesIo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    createSubTable(row){
      createSubTable(row.id).then( res => this.$modal.msgSuccess("创建成功!"))
    },
    indexMethod(index){
      return '选项'+(index+1)
    },
    openDeviceTask(){
      this.deviceTaskVisiabled = true
    },
    onSelectDeviceTask(optList){
      console.log(optList)
      this.optionList = optList;
      this.form.commandList = optList;
      this.deviceTaskVisiabled = false
    },
    cancelDeviceTask(){
      this.deviceTaskVisiabled = false
    },
    openGwTask(){
      this.gwTaskVisiabled = true
    },
    onSelectGwTask(obj){
      this.optionList = obj.commandList;
      this.form.commandList = obj.commandList;
      this.form.valueExpression = obj.valueExpression;
      this.gwTaskVisiabled = false
    },
    cancelGwTask(){
      this.gwTaskVisiabled = false
    },
    addOption(){
      this.optionList.push({
        id:null,
        name:'',
        value:'',
        expression:'EQ'
      })
      this.$nextTick()
    },
    delOption(index,row){
      this.optionList.splice(index,1)
    },
    handleRemove() {
      this.form.icon = '';
    },
    uploadSuccess(res) {
      this.$set(this.form, 'icon', res.data.id)
      this.$refs["form"].clearValidate('icon')
    },
    selectIcon(){
      this.targetIcon = this.form.icon;
      this.iconPopup = true;
    },
    onIconChange(value){
      this.targetIcon = value;
    },
    handleSelect(){
      if(this.targetIcon){
        this.form.icon = this.targetIcon;
        this.iconPopup = false;
      }
    },
    toDisplay(row){
      this.$router.push({
        path: '/seriesIoDisplay/display',
        query: { sensorId:row.id , name:row.name}
      })
    } ,
    toEvent(row){
      this.$router.push({
        path: '/seriesIoEvent/event',
        query: { sensorId:row.id , name:row.name , deviceTypeId:row.deviceTypeId}
      })
    } ,
  }
};
</script>


<style  lang="scss" scoped >
.option-box{
  text-align: right;
  .add-btn{
    margin-top: 10px;
  }
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
</style>